package org.example.session;

import org.example.config.Configuration;
import org.example.executor.Executor;
import org.example.mapping.MappedStatement;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private final Configuration configuration;
    private final Executor executor;

    private final boolean autoCommit;

    public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
        this.configuration = configuration;
        this.executor = executor;
        this.autoCommit = autoCommit;
    }


    @Override
    public <T> T selectOne(String statement) {
        return selectOne(statement,null);
    }

    @Override
    public <T> T selectOne(String statement, Object parameter) {
        List<T> objects = selectList(statement,parameter,RowBounds.DEFAULT);
        if(null == objects)return null;

        if(objects.size()==1){
            return objects.get(0);
        }else if(objects.size() > 1){
            throw new RuntimeException("too many results");
        }
        return null;
    }

    @Override
    public <E> List<E> selectList(String statement) {
        return selectList(statement,null,null);
    }

    @Override
    public <E> List<E> selectList(String statement, Object parameter,RowBounds rowBounds) {
        MappedStatement mappedStatement = configuration.getMappedStatements().get(statement);
        try {
            return executor.query(mappedStatement,parameter,rowBounds,null);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public <T> T getMapper(Class<T> type) {
        return configuration.getMapper(type, this);
    }

    @Override
    public Configuration getConfiguration() {
        return configuration;
    }

    @Override
    public void close() throws IOException {

    }
}
